#!/usr/bin/env bash
# Extract all ```json code blocks from a Markdown file and write them
# as a JSON array to the given output path.
# Usage: ./tools/extract_md_json_blocks.sh <input.md> <output.json>

set -euo pipefail

if [ "$#" -ne 2 ]; then
  echo "Usage: $0 <input.md> <output.json>" >&2
  exit 1
fi

in="$1"
out="$2"

if [ ! -f "$in" ]; then
  echo "Input file not found: $in" >&2
  exit 1
fi

# Create output directory if needed
mkdir -p "$(dirname "$out")"

# awk state machine:
# - When encountering a line starting with ```json, enter json block state
# - While in block, print lines verbatim
# - When encountering a line starting with ```, close the block
# - Emit commas between blocks, wrap with [ ]

awk '
  BEGIN {
    in_block = 0;
    block_count = 0;
    print "[";
  }
  /^?```json/ {
    in_block = 1;
    if (block_count > 0) {
      printf(",\n");
    }
    next;
  }
  /^?```/ {
    if (in_block == 1) {
      in_block = 0;
      block_count++;
      next;
    }
  }
  {
    if (in_block == 1) {
      print $0;
    }
  }
  END {
    print "\n]";
  }
' "$in" > "$out.tmp"

# Basic sanity: output should start with [ and end with ]
if head -n1 "$out.tmp" | grep -q "^\[" && tail -n1 "$out.tmp" | grep -q "^]$"; then
  mv -f "$out.tmp" "$out"
  echo "Wrote JSON array with extracted blocks: $out"
else
  echo "Extraction failed to produce a JSON array: $out.tmp" >&2
  exit 2
fi

exit 0

